<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */


class Core_Service_Privilege extends RedCross_Service_ServiceAbstract
{
    public function __construct(Core_Gateway_Privilege $gateway)
    {
        parent::__construct($gateway, 'Core_Model_Privilege');
    }

    public function fetchAllByGroup($groupId)
    {
        $this->checkAcl('fetch');
        return $this->getGateway()->fetchAllByGroup($groupId);
    }

    public function fetchAllResourcesWithPrivileges()
    {
        $this->checkAcl('fetch');
        return $this->getGateway()->fetchAllResourcesWithPrivileges();
    }

    public function savePrivileges($groupId, array $data)
    {
        $this->checkAcl('save');

        // Create a Transaction
        $manager = Doctrine_Manager::getInstance();
        $conn = $manager->getCurrentConnection();
        $conn->beginTransaction();

        // Remove all privileges for the group
        $this->getGateway()->removeGroupPrivileges($groupId);

        // Add privileges to the group
        foreach ($data as $resource => $privileges) {
            if ($privileges === null) {
            	continue;
            }

            foreach ($privileges as $p) {
                $groupPrivilege = new RedCross_Gateway_Base_GroupPrivilege();
                $groupPrivilege->group_id = $groupId;
            	$groupPrivilege->privilege_id = $p;
            	$groupPrivilege->save();
            }
        }

        try {
            $conn->commit();
            $cacheManager = Zend_Registry::get('cacheManager');
            $cache = $cacheManager->getCache('acl');
            $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('acl_object'));

            $cache = $cacheManager->getCache('navigation');
            $cache->clean(Zend_Cache::CLEANING_MODE_ALL);

            $cache = $cacheManager->getCache('navigationOutput');
            $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
        } catch (Doctrine_Exception $e) {
            $conn->rollback();
        }
    }

}